﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security;
using Microsoft.Win32;

namespace jSLCore.VSPackageRegistering
{
    public static class RegistryHelper
    {
         public static IEnumerable<RegistryKey> FindSubKey(this RegistryKey registryKey,string name)
         {
             var result = new List<RegistryKey>(20);
             var names = registryKey.GetSubKeyNames();

             foreach (var itemName in names)
             {
                 try
                 {
                     var openSubKey = registryKey.OpenSubKey(itemName);

                     if (openSubKey != null)//todo: непонятно, но почему то он может быть null, почему?
                     {

                         if (itemName.ToUpper() == name.ToUpper())
                         {
                             result.Add(registryKey.OpenSubKey(itemName, true));
                         }
                         else
                         {
                             result.AddRange(openSubKey.FindSubKey(name));
                         }
                     }
                 }
                 catch (SecurityException)
                 {
                     continue;
                 }
             }
             return result;
         }
    }
}